package com.wfh.frp.coder;

import com.wfh.frp.model.ProxyMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Title: ProxMsgEncoder
 * @Author wangfenghuan
 * @Package com.wfh.frp.coder
 * @Date 2025/10/8 09:52
 * @description: 编码器
 */
@Slf4j
public class ProxMsgEncoder extends MessageToByteEncoder<ProxyMsg> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ProxyMsg msg, ByteBuf out) throws Exception {
        log.info("msg encode: {}", msg);

        int startIdx = out.writerIndex();
        out.writeInt(0); // 预留4字节写总长度

        // 1. 写 channelId
        if (msg.getChannelId() != null) {
            byte[] idBytes = msg.getChannelId().getBytes(StandardCharsets.UTF_8);
            out.writeInt(idBytes.length);
            out.writeBytes(idBytes);
        } else {
            out.writeInt(-1);
        }

        // 2. 写 dataLen（= 1 + data.length）
        int dataLen = 1;
        if (msg.getData() != null) {
            dataLen += msg.getData().length;
        }
        out.writeInt(dataLen);

        // 3. 写 type
        out.writeByte(msg.getType());

        // 4. 写 data
        if (msg.getData() != null) {
            out.writeBytes(msg.getData());
        }

        // 5. 回填总长度（不包含长度字段自身）
        int totalLength = out.writerIndex() - startIdx - 4;
        out.setInt(startIdx, totalLength);
    }
}